<template>
  <div class="patrol-map-container">
    <div class="patrol-header">
      <h2>巡更地图</h2>
      <el-select
          v-model="selectedCommunity"
          placeholder="选择小区"
          @change="loadPatrolPoints"
          style="width: 200px; margin-right: 10px;"
      >
        <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
        ></el-option>
      </el-select>
      <el-select
          v-model="selectedRoute"
          placeholder="选择路线"
          @change="loadRoutePoints"
          style="width: 200px; margin-right: 10px;"
      >
        <el-option
            v-for="route in routeList"
            :key="route.routeId"
            :label="route.routeName"
            :value="route.routeId"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="startPatrol" :disabled="isPatrolling">
        {{ isPatrolling ? '正在巡更中' : '开始巡更' }}
      </el-button>
      <el-button
          type="danger"
          @click="exitPatrol"
          :disabled="!isPatrolling"
          style="margin-left:10px;"
      >
        退出巡更
      </el-button>
    </div>

    <!-- 地图容器 -->
    <div class="map-container" ref="mapContainer"></div>

    <!-- 巡更点位列表 -->
    <el-card style="margin-top: 20px;">
      <div slot="header">
        <h3>巡更点位列表</h3>
      </div>
      <el-table
          :data="patrolPoints"
          border
          style="width: 100%;"
      >
        <el-table-column prop="pointName" label="巡更点名称" width="120" />
        <el-table-column prop="locationCode" label="位置编号" width="100" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
                size="small"
                type="success"
                @click="checkIn(scope.row)"
                :disabled="!isPatrolling"
            >
              签到
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 签到弹窗 -->
    <el-dialog
        title="巡更签到"
        v-model="checkInDialogVisible"
        width="400px"
    >
<!--      <div v-if="!checkInDialogVisible" style="color: red; margin-bottom: 10px;">-->
<!--        调试：弹窗当前隐藏-->
<!--      </div>-->
<!--      <div v-else style="color: green; margin-bottom: 10px;">-->
<!--        调试：弹窗当前显示-->
<!--      </div>-->

      <el-form :model="checkInForm" ref="checkInFormRef">
        <el-form-item label="巡更点位" prop="pointName">
          <el-input v-model="checkInForm.pointName" disabled />
        </el-form-item>

        <el-form-item label="定位状态">
          <el-tag :type="locationStatusType">{{ locationStatusText }}</el-tag>
        </el-form-item>

        <el-form-item label="巡检结果" prop="result">
          <el-radio-group v-model="checkInForm.result">
            <el-radio value="正常">正常</el-radio>
            <el-radio value="异常">异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="异常说明" prop="remark" v-if="checkInForm.result === '异常'">
          <el-input type="textarea" v-model="checkInForm.remark" rows="3" />
        </el-form-item>

        <!-- 照片上传区域 -->
        <el-form-item label="现场照片" prop="photoUrls" v-if="currentPoint?.photoRequired">
          <el-upload
              action=""
              :on-change="handlePhotoUpload"
              :show-file-list="false"
              accept="image/*"
              :auto-upload="false"
              multiple
          >
            <el-button size="small" type="primary">上传照片</el-button>
          </el-upload>

          <div class="photo-preview-list" v-if="checkInForm.photoUrls.length">
            <div v-for="(url, index) in checkInForm.photoUrls" :key="index" class="photo-item">
              <img :src="url" class="preview-img" />
              <el-button
                  size="small"
                  @click="checkInForm.photoUrls.splice(index, 1)"
                  style="color: #f56c6c;"
              >
                删除
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>




      <div slot="footer">
        <el-button @click="checkInDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCheckIn" :disabled="!isLocationValid">确认签到</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getPointByCommunity, getPointByRoute, validateLocation as validateLocationApi} from '../api/patrolPoint'
import { getCommunityList } from '../api/community'
import { submitRecord } from '../api/patrolRecord.js'
import { getRouteByCommunity } from '../api/patrolRoute'
import { getCategoryByCommunity } from '../api/patrolCategory'
import loadBMap from '../utils/loadBMap.js';
import { uploadImage } from '../api/uploadApi.js'
import {useRoute, useRouter} from "vue-router";
import router from "../router/index.js";
import {updateTaskStatus} from "../api/PatrolTask.js";
const checkedRecords = ref({});

export default {
  name: 'PatrolMap',
  setup() {
    const route = useRoute();
    const router = useRouter();
    // 社区列表
    const communityList = ref([])
    // 路线列表
    const routeList = ref([])
    // 地图相关
    const mapContainer = ref(null)
    const map = ref(null)
    const markers = ref([])
    // 新增定位相关状态
    const locationStatusText = ref('未获取位置')
    const locationStatusType = ref('info')
    const isLocationValid = ref(false)
    const currentPosition = ref(null)
    // 数据状态
    const selectedCommunity = ref(1)
    const selectedRoute = ref(null)
    const patrolPoints = ref([])
    const loading = ref(false)
    const isPatrolling = ref(false)

    // 签到表单
    const checkInDialogVisible = ref(false)
    const currentPoint = ref(null)
    const checkInForm = ref({
      pointId: null,
      pointName: '',
      result: '正常',
      remark: '',
      photoUrls: []
    })
    const checkInFormRef = ref(null)

    // 加载小区列表
    const loadCommunityList = async () => {
      try {
        let {data:data} = await getCommunityList()
        console.log('加载小区列表结果',data)
        if (data.code === 0) {
          communityList.value = data.data
          if (communityList.value.length > 0) {
            selectedCommunity.value = communityList.value[0].id
          }
        } else {
          ElMessage.error(data.msg || '加载小区列表失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，无法加载小区列表')
        console.error('加载小区失败:', error)
      }
    }

    // 加载路线列表
    const loadRouteList = async () => {
      if (!selectedCommunity.value) return;
      try {
        let {data:data} = await getRouteByCommunity(selectedCommunity.value)
        console.log(data)
        if (data.code === 0) {
          routeList.value = data.data
          selectedRoute.value = null
        } else {
          ElMessage.error(data.msg || '加载路线失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('加载路线失败:', error)
      }
    }

    // 加载巡更点位
    const loadPatrolPoints = async () => {
      if (!selectedCommunity.value) return;
      try {
        loading.value = true
        let {data:data} = await getPointByCommunity(selectedCommunity.value)
        if (data.code === 0) {
          patrolPoints.value = data.data
          drawPatrolPoints()
        } else {
          ElMessage.error(data.msg)
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('加载点位失败:', error)
      } finally {
        loading.value = false
      }
    }
// 获取当前位置
    const getCurrentPosition = () => {
      return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
              position => resolve(position),
              error => reject(error),
              { timeout: 10000 }
          )
        } else {
          reject(new Error('浏览器不支持地理定位'))
        }
      })
    }

    // 校验定位
    const validateLocation = async (pointId, position) => {
      try {
        const { latitude, longitude } = position.coords
        let {data:data} = await validateLocationApi(pointId, latitude, longitude)
        console.log('API返回数据:',data)
        if (data.code === 0 && data.data.valid) {
          locationStatusText.value = `定位成功，距离 ${data.data.distance} 米`
          locationStatusType.value = 'success'
          isLocationValid.value = true
          return true
        } else {
          locationStatusText.value = `定位失败，距离 ${data.data.distance} 米（超出范围）`
          locationStatusType.value = 'danger'
          isLocationValid.value = false
          return false
        }
      } catch (error) {
        console.error('定位校验失败', error)
        locationStatusText.value = '定位校验失败，请重试'
        locationStatusType.value = 'danger'
        isLocationValid.value = false
        return false
      }
    }
    // 加载路线点位
    const loadRoutePoints = async () => {
      if (!map.value) {
        ElMessage.error('地图未准备好，请稍后重试');
        return; // 地图未初始化则终止
      }
      if (!selectedRoute.value) return;
      try {
        loading.value = true;
        let {data:data} = await getPointByRoute(selectedRoute.value);
        if (data.code === 0) {
          patrolPoints.value = data.data;
          // 恢复签到状态
          patrolPoints.value.forEach(point => {
            const key = `${selectedRoute.value}-${point.pointId}`;
            if (checkedRecords.value[key]) {
              point.status = '已巡检'; // 从全局记录恢复
            }
          });
          // ---------- 步行路线规划改造开始 ----------
          if (patrolPoints.value.length > 1) {
            const BMapGL = await loadBMap('BhXLEe1ldliYZqVAn4VC5CiwTqlyGOtT'); // 替换为你的AK
            const waypoints = patrolPoints.value.map(p =>
                new BMapGL.Point(p.longitude, p.latitude)
            );

            // 初始化步行路线规划
            const walking = new BMapGL.WalkingRoute(map.value, {
              renderOptions: { map: map.value, autoViewport: true }, // 自动渲染到地图并调整视野
              onRouteComplete: (result) => {
                if (result.getStatus() === BMapGL.BMAP_STATUS_SUCCESS) {
                  ElMessage.success('步行路线已按实际道路规划');
                } else {
                  ElMessage.error('步行路线规划失败， fallback 到直线绘制');
                  //  fallback：若规划失败，仍绘制直线
                  const polyline = new BMapGL.Polyline(waypoints, {
                    strokeColor: "#1677ff",
                    strokeWeight: 4,
                    strokeOpacity: 0.8
                  });
                  map.value.addOverlay(polyline);
                }
              },
            });

            // 发起步行路径规划（起点=第一个点位，终点=最后一个点位，途经点=中间点位）
            walking.search(
                waypoints[0],
                waypoints[waypoints.length - 1],
                { waypoints: waypoints.slice(1, -1) } // 排除起点和终点，作为途经点
            );
          }
          // ---------- 步行路线规划改造结束 ----------
          drawPatrolPoints();
        } else {
          ElMessage.error(data.message || '加载路线点位失败');
          console.error('接口返回错误:', data);
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
        console.error('加载路线点位失败:', error);
      } finally {
        loading.value = false;
      }
    };

    // 绘制点位到地图（核心修改：优化按钮事件绑定）
    const drawPatrolPoints = () => {
      if (!map.value) {
        ElMessage.warning('地图未加载完成，暂无法显示点位');
        return;
      }

      // 清除现有标记
      if (markers.value.length > 0) {
        markers.value.forEach(item => {
          map.value.removeOverlay(item.marker);
          map.value.removeOverlay(item.label);
        });
        markers.value = [];
      }

      patrolPoints.value.forEach(point => {
        const position = new BMapGL.Point(point.longitude, point.latitude);

        // 1. 创建点位标记
        const marker = new BMapGL.Marker(position, {
          color: point.status === '已巡检' ? '#dd1b1b' : '#36abab',
          size: new BMapGL.Size(16, 16),
          shape: BMapGL.MARKER_SHAPE_CIRCLE
        });

        // 2. 创建签到按钮（作为独立覆盖物，不依赖信息窗口）
        const btn = document.createElement('div');
        btn.innerHTML = '签到';
        btn.style.cssText = `
          padding: 3px 8px;
          background: #1677ff;
          color: white;
          border: none;
          border-radius: 3px;
          cursor: pointer;
          font-size: 12px;
          margin-top: 5px;
        `;
        // 按钮点击事件（直接绑定）
        btn.onclick = () => {
          if (isPatrolling.value) {
            checkIn(point);
          } else {
            ElMessage.warning('请先开始巡更');
          }
        };
        const label = new BMapGL.Label(btn, {
          position: position,
          offset: new BMapGL.Size(20, 0) // 显示在标记右侧
        });
        label.setStyle({
          border: 'none',
          padding: '0'
        });

        // 3. 信息窗口（仅展示信息，不含按钮）
        const infoWindowContent = `
      <div style="padding:10px">
        <h4>${point.pointName}</h4>
        <p>位置：${point.locationCode || '未知'}</p>
        <p>分类：${point.categoryName}</p>
        <p>状态：${point.status || '未巡检'}</p>
        <p>拍照要求：${point.photoRequired ? '是' : '否'}</p>
      </div>
    `;
        const infoWindow = new BMapGL.InfoWindow(infoWindowContent);
        marker.addEventListener('click', () => {
          map.value.openInfoWindow(infoWindow, position);
        });

        // 4. 添加到地图
        map.value.addOverlay(marker);
        map.value.addOverlay(label); // 添加按钮覆盖物
        markers.value.push({marker, label}); // 保存标记和按钮，便于后续清除
      })
    };

    // 初始化地图
    const initMap = async () => {
      if (!mapContainer.value) return;
      try {
        const BMapGL = await loadBMap('BhXLEe1ldliYZqVAn4VC5CiwTqlyGOtT');
        map.value = new BMapGL.Map(mapContainer.value);
        const centerPoint = new BMapGL.Point(116.404, 39.915);
        map.value.centerAndZoom(centerPoint, 15);
        map.value.addControl(new BMapGL.NavigationControl());
        map.value.addControl(new BMapGL.ScaleControl());
        ElMessage.success('地图加载成功');
      } catch (error) {
        ElMessage.error('地图API加载失败，请刷新页面重试');
        console.error('地图加载失败:', error);
      }
    };

    // 开始巡更
    const startPatrol = () => {
      if (!selectedRoute.value) {
        ElMessage.warning('请先选择巡更路线')
        return
      }
      isPatrolling.value = true
      ElMessage.success('开始巡更，请按路线依次签到')
    }
    // 退出巡更
    const exitPatrol = () => {
      isPatrolling.value = false;
      // 可选：清空当前路线的签到记录
      // Object.keys(checkedPoints.value).forEach(key => {
      //   if (key.startsWith(selectedRoute.value)) {
      //     delete checkedPoints.value[key];
      //   }
      // });
      ElMessage.success('已退出巡更');
    };

    // 签到操作（简化弹窗显示逻辑）添加定位校验
    const checkIn = async (point) => {
      console.log('触发签到方法:', point, '当前巡更状态:', isPatrolling.value);
      if (!isPatrolling.value) {
        ElMessage.warning('请先开始巡更');
        return;
      }
      if (!point?.pointId) {
        ElMessage.error('点位数据异常，无法签到');
        return;
      }
      // 重置定位状态
      locationStatusText.value = '正在获取位置...'
      locationStatusType.value = 'info'
      isLocationValid.value = false

      try {
        // 获取当前位置
        const position = await getCurrentPosition()
        currentPosition.value = position

        // 校验位置
        const isValid = await validateLocation(point.pointId, position)

        if (!isValid) {
          ElMessage.warning('你当前不在巡更点有效范围内，无法签到')
          return
        }

        // 位置校验通过，继续处理签到
        currentPoint.value = JSON.parse(JSON.stringify(point));
        checkInForm.value = {
          pointId: point.pointId,
          pointName: point.pointName,
          result: '正常',
          remark: '',
          photoUrls: []
        };

        checkInDialogVisible.value = true;
        console.log('弹窗状态更新为:', checkInDialogVisible.value);
      } catch (error) {
        console.error('获取位置失败', error)
        locationStatusText.value = '获取位置失败，请检查权限'
        locationStatusType.value = 'danger'
        isLocationValid.value = false
        ElMessage.error('获取位置失败，请确保您的浏览器已授予位置权限')
      }
    }

    // 处理照片上传
    const handlePhotoUpload = async (file) => {
      if (!file.raw.type.startsWith('image/')) {
        ElMessage.error('请上传图片格式文件');
        return;
      }
      try {
        let {data:data} = await uploadImage(file.raw);
        console.log('MinIO 返回的完整数据：', data);
        if (data.code === 0) {
          const imgUrl = data.msg;
          // 打印并手动验证 URL
          console.log('图片 URL：', imgUrl);
          // 可临时在浏览器新标签页打开 imgUrl，确认是否能访问
          checkInForm.value.photoUrls.push(imgUrl);
          ElMessage.success(`已上传 ${checkInForm.value.photoUrls.length} 张照片`);
        } else {
          ElMessage.error('上传失败：' + data.msg);
        }
      } catch (error) {
        ElMessage.error('上传接口调用失败，请重试');
        console.error('图片上传错误：', error);
      }
    };

    // 确认签到
    const confirmCheckIn = async () => {
      if (!isLocationValid.value) {
        ElMessage.warning('定位校验未通过，无法签到');
        return;
      }
      const taskId = route.query.taskId;
      if (!taskId) {
        ElMessage.error('未关联任务ID，签到失败');
        return;
      }

      if (currentPoint.value?.photoRequired && checkInForm.value.photoUrls.length === 0) {
        ElMessage.warning('该点位需要上传现场照片');
        return;
      }

      // 最外层 try
      try {
        const recordData = {
          pointId: checkInForm.value.pointId,
          patrolResult: checkInForm.value.result,
          remark: checkInForm.value.remark,
          photoUrls: checkInForm.value.photoUrls.join(','),
          taskId: taskId,
          categoryId: currentPoint.value.categoryId,
          categoryName: currentPoint.value.categoryName,
          longitude: currentPoint.value.longitude,
          latitude: currentPoint.value.latitude,
          pointName: currentPoint.value.pointName,
          areaName: currentPoint.value.areaName,
          createBy: '',
          updateBy: '',
          checkinRadius: currentPoint.value.checkinRadius
        };

        let {data:data} = await submitRecord(recordData);
        if (data.code === 0) {
          ElMessage.success('签到成功');
          checkInDialogVisible.value = false;

          // 更新点位状态
          const pointIndex = patrolPoints.value.findIndex(p => p.pointId === checkInForm.value.pointId);
          if (pointIndex !== -1) {
            patrolPoints.value[pointIndex].status = '已巡检';
            drawPatrolPoints();
          }

          // 检查是否所有点位完成
          const allCompleted = patrolPoints.value.every(p => p.status === '已巡检');
          if (allCompleted) {
            // 嵌套的 try-catch（已完整，无需修改）
            try {
              if (!taskId || isNaN(Number(taskId))) {
                ElMessage.error('任务ID无效，无法更新状态');
                return;
              }
              const targetStatus = 2; //目标状态：已完成
              if (targetStatus < 0 || targetStatus > 5) {
                ElMessage.error('无效的任务状态值');
                return;
              }

              // 正确调用：参数通过 data 传递，且类型正确
              const updateRes = await updateTaskStatus({
                taskId: Number(taskId),  // 确保为数字类型
                status: targetStatus,    // 状态值为数字（0-5）
                remark: '所有点位巡检完成'  // 字符串类型
              });

              if (updateRes.data && updateRes.data.code === 0) {
                ElMessage.success('任务已标记为已完成');
                await router.push('/task');
              } else {
                ElMessage.error('任务状态更新失败: ' + (updateRes.data?.message || '未知错误'));
              }
            } catch (error) {
              console.error('更新任务状态失败:', error);
              if (error.response) {
                console.log('错误状态码:', error.response.status);
                console.log('后端返回错误:', error.response.data);
                console.log('请求参数:', error.config.data);
              }
              ElMessage.error('更新任务状态接口调用失败（参数错误）');
            }
          }
        } else {
          // 接口返回失败的处理
          ElMessage.error('签到失败: ' + (data.message || '未知错误'));
        }
      } catch (error) {
        // 新增：最外层 try 的 catch 子句，捕获整个签到过程的错误
        console.error('签到提交过程发生错误:', error);
        ElMessage.error('签到过程失败，请稍后重试');
      }
    };

    // 组件挂载时初始化
    onMounted(async () => {
      // 1. 先初始化地图（必须第一步完成）
      await initMap();
      if (!map.value) {
        ElMessage.error('地图初始化失败，无法加载巡更点位');
        return;
      }

      // 2. 再加载社区和路线列表
      await loadCommunityList();
      await loadRouteList();

      // 3. 处理路由参数（任务ID和路线ID）
      const taskId = route.query.taskId;
      const routeIds = route.query.routeIds;

      if (taskId && routeIds) {
        // 4. 加载路线点位（此时map已初始化）
        selectedRoute.value = routeIds.split(',')[0];
        await loadRoutePoints(); // 现在调用drawPatrolPoints时map已存在

        // 5. 自动开始巡更（符合文档“点击处理后直接进入巡更”）
        isPatrolling.value = true;
        ElMessage.success(`已开始任务#${taskId}的巡更`);
      }
    });

    // 监听小区变化
    watch(selectedCommunity, (newVal) => {
      if (newVal) {
        loadRouteList();
        loadPatrolPoints();
      }
    })

    // 组件卸载时清理
    onUnmounted(() => {
      if (map.value) {
        // 清除标记和按钮覆盖物
        markers.value.forEach(item => {
          map.value.removeOverlay(item.marker);
          map.value.removeOverlay(item.label);
        });
        map.value.clearOverlays();
        map.value = null;
      }
    });

    return {
      communityList,
      selectedCommunity,
      routeList,
      selectedRoute,
      mapContainer,
      patrolPoints,
      loading,
      isPatrolling,
      checkInDialogVisible,
      currentPoint,
      checkInForm,
      checkInFormRef,
      loadRouteList,
      loadPatrolPoints,
      loadRoutePoints,
      startPatrol,
      checkIn,
      handlePhotoUpload,
      exitPatrol,
      confirmCheckIn,
      locationStatusText,
      locationStatusType,
      isLocationValid
    };
  }
};
</script>

<style scoped>
.patrol-map-container {
  padding: 20px;
}

.patrol-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.map-container {
  width: 100%;
  height: 400px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}

/* 照片预览样式 */
.photo-preview-list {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  flex-wrap: wrap;
}

.photo-item {
  position: relative;
}

.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border: 1px solid #eee;
  border-radius: 4px;
}

.photo-item .el-button {
  position: absolute;
  bottom: 0;
  right: 0;
  padding: 2px 5px;
  line-height: 1;
  background: rgba(255, 255, 255, 0.8);
}

/* 地图签到按钮样式 */
.map-checkin-btn {
  cursor: pointer;
}
</style>